const CanvasHelper = require('./canvas-helper');

class UiHelper {
  constructor() {
    this.selector = wx.createSelectorQuery();
  }

  getContext(elementId) {
    return new Promise((resolve, _reject) => {
      this.selector
        .select(`#${elementId}`)
        .context((res) => resolve(res.context))
        .exec();
    });
  }

  getNodeFields(elementId, options) {
    return new Promise((resolve, _reject) => {
      this.selector
        .select(`#${elementId}`)
        .fields(options)
        .exec((res) => {
          console.log(res);
          resolve(res);
        });
    });
  }

  buildCanvasHelper(canvasId) {
    return this.getNodeFields(canvasId, {
      node: true,
      size: true,
    }).then((res) => {
      console.log(res);
      const canvas = res[1].node;
      const ctx = canvas.getContext('2d');
      const dpr = wx.getWindowInfo().pixelRatio;
      canvas.width = res[1].width * dpr;
      canvas.height = res[1].height * dpr;
      ctx.scale(dpr, dpr);
      return new CanvasHelper(canvasId, canvas, ctx);
    });
  }

  writeContentByCtx(ctx, content) {
    return new Promise((resolve, reject) => {
      ctx.setContents({
        html: content,
        success: function () {
          resolve(content);
        },
        fail: function (err) {
          reject(err);
        },
      });
    });
  }

  writeContent(elementId, content) {
    return this.getContext(elementId).then((ctx) => this.writeContentByCtx(ctx, content));
  }

  readContentByCtx(ctx) {
    return new Promise((resolve, reject) => {
      ctx.getContents({
        success: function (res) {
          resolve(res.html);
        },
        fail: function (err) {
          reject(err);
        },
      });
    });
  }

  readContent(elementId) {
    return this.getContext(elementId).then((ctx) => this.readContentByCtx(ctx));
  }

  switchTab(url) {
    return new Promise((resolve, reject) => {
      wx.switchTab({
        url,
        success: resolve,
        fail: reject,
      });
    });
  }

  boundingClientRect(elementId) {
    return new Promise((resolve, _reject) => {
      this.selector
        .select(`#${elementId}`)
        .boundingClientRect((rect) => resolve(rect))
        .exec();
    });
  }

  saveCanvasToTempFile(canvasId) {
    return new Promise((resolve, reject) => {
      wx.canvasToTempFilePath({
        canvasId: canvasId,
        success: resolve,
        fail: reject,
      });
    });
  }

  pageScrollTo(options) {
    return new Promise((resolve, reject) => {
      wx.pageScrollTo({
        ...options,
        success: resolve,
        fail: reject,
      });
    });
  }
}

module.exports = UiHelper;
